// 基于axios封装网络请求
import newAxios from 'axios'
import {
  getToken, removeToken, setToken
}
from '@/utils/token' //
import router from '@/router'
import {
  Notify
} from 'vant'
import {
  refreshTokenAPI
} from '@/api'
const axios = newAxios.create({
  baseURL: 'http://toutiao.itheima.net',
  timeout: 20000
})

// 配置响应拦截器
axios.interceptors.response.use(function (response) {
  return response
}, async function (err) {
  // 身份过期  跳转登录页
  if (err.response.status === 401) {
    Notify({
      type: 'warning',
      message: '身份已过期 '
    })
    // 方式1
    removeToken()
    // router.replace('/login')

    // 方式二 续费token
    const result = await refreshTokenAPI()
    // console.log(result)
    setToken(result.data.data.token)
    err.config.headers.Authorization = `Bearer ${result.data.data.token}`
    return axios(err.config)
  } else if (err.response.status === 500 && err.config.url === '/v1_0/authorizations' && err.config.method === 'put') {
    removeToken()
    localStorage.removeItem('refresh_token')
    router.replace(`/login?path=${router.currentRoute.fullPath}`)
  }
  return Promise.reject(err)
})

// 配置请求拦截器
axios.interceptors.request.use(function (config) {
  // 判断本地有TOken没,判断携带Authorization,没有则添加
  if (getToken() && config.headers.Authorization === undefined) {
    config.headers.Authorization = `Bearer ${getToken()} `
  }
  return config
}, function (err) {
  return Promise.reject(err)
})

export default ({ url, method = 'GET', params = {}, data = {}, headers = {} }) => {
  return axios({
    url,
    method,
    params,
    data,
    headers
  })
}
